package com.book.lizhi.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.EncodingUtils;

import android.content.Context;

import com.book.lizhi.AppApplication;
import com.book.lizhi.constants.Constants;
import com.book.lizhi.database.DiskLruCache;

public class FileUtil {

	private static DiskLruCache diskLruCache;

	public static DiskLruCache getDiskLruCache() {
		if (diskLruCache == null) {
			try {
				diskLruCache = DiskLruCache.open(getCacheFile(), Util.getPackageVersion(), 1, 10 * 1024 * 1024);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return diskLruCache;
	}

	public static void writeFile(Context context, InputStream inputStream, String fileName) {
		try {
			int len = inputStream.available();
			byte[] buffer = new byte[len];
			inputStream.read(buffer);
			String contentString = EncodingUtils.getString(buffer, "UTF-8");

			FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			outputStream.write(contentString.getBytes());
			outputStream.flush();
			outputStream.close();
			inputStream.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static File getCacheFile() {
		File file;
		if (AppApplication.instance.getExternalCacheDir() != null) {
			file = new File(AppApplication.instance.getExternalCacheDir(), Constants.CACHE);
		} else {
			file = new File(AppApplication.instance.getCacheDir(), Constants.CACHE);

		}
		if (!file.exists()) {
			file.mkdirs();
		}
		return file;
	}

	public static File getBitmapCache() {
		File file = new File(getCacheFile(), Constants.COVER_CACHE);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file;
	}

	public static List<String> getLocalChapterName(String bid) {
		List<String> names = new ArrayList<String>();
		File bookFile = new File(getCacheFile(), bid);
		File[] files = bookFile.listFiles();
		for (File file : files) {
			names.add(file.getName());
		}
		return names;
	}

	public static void storeChapter(String bid, String cid, String content) {
		try {
			File floder = new File(FileUtil.getCacheFile() + File.separator + bid);
			if (!floder.exists()) {
				floder.mkdir();
			}
			File cidFile = new File(floder, cid);
			if (!cidFile.exists()) {
				cidFile.createNewFile();
			}
			FileWriter writer = new FileWriter(cidFile);
			writer.write(content);
			writer.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static boolean isLoadChapter(String bid, String cid) {
		File file = new File(getCacheFile(), bid);
		File cidFile = new File(file, cid);
		return cidFile.exists() && cidFile.length() > 0;
	}

	public static String findChapter(String bid, String cid) {
		File file = new File(getCacheFile(), bid);
		File cidFile = new File(file, cid);
		return cidFile.getAbsolutePath();
	}

	public static File getBookmarkList(String bid) {
		File file = new File(getCacheFile(), bid);
		File cidFile = new File(file, "bookmark");
		return cidFile;
	}

	public static File getChapterList(String bid) {
		File file = new File(getCacheFile(), bid);
		File cidFile = new File(file, "chapterList");
		return cidFile;
	}

	public static void deleteCacheFile() {
		File cacheFile = getCacheFile();
		deleteFile(cacheFile);
	}

	public static void saveStringByKey(String key, String json) {
		AppLog.e("key:"+key+"\n"+"json:"+json);
		try {
			File file = new File(getCacheFile(), key);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter writer = new FileWriter(file);
			writer.write(json);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getStringByKey(String key) {
		File file = new File(getCacheFile(), key);
		if (file != null && file.exists()) {
			try {
				return readContent(new FileInputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		return null;

	}

	public static String readContent(InputStream inputStream) {
		String strContent = "", strLine = "";
		try {
			InputStreamReader read = new InputStreamReader(inputStream, "utf-8");
			BufferedReader reader = new BufferedReader(read);
			while ((strLine = reader.readLine()) != null) {
				strContent += strLine;
			}
			reader.close();
			read.close();
		} catch (IOException e) {
			String strErrMsg = e.getMessage();
			System.out.println("Read file " + " failed! Error message:" + strErrMsg);
		}
		return strContent;
	}

	/**
	 * 删除文件夹所有内容
	 * 
	 */
	public static void deleteFile(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		}
	}
}
